import React, {Component, useState} from 'react';
import {StyleSheet, ScrollView, Alert} from 'react-native';
import {
  Colors,
  Modal,
  View,
  Text,
  Button,
  Assets,
  Spacings,
  Typography,
} from 'react-native-ui-lib';
import {TestCase, TestSuite} from '@rnoh/testerino';

Assets.loadAssetsGroup('demo', {
  close: require('../../assets/icons/close.png'),
  check: require('../../assets/icons/check.png'),
  search: require('../../assets/icons/search.png'),
});

interface ModalTesterProps {
  label: string;
  modalProps?: React.ComponentProps<typeof Modal>;
  topBarProps?: React.ComponentProps<typeof Modal.TopBar>;
  children?: React.ReactNode;
  isFullScreen?: boolean;
}

const ModalTester = ({
  label,
  modalProps = {},
  topBarProps,
  children,
  isFullScreen = false,
}: ModalTesterProps) => {
  const [visible, setVisible] = useState(false);
  const [eventLogs, setEventLogs] = useState<{[key: string]: number}>({});

  const addLog = (eventName: string) => {
    setEventLogs(prev => ({
      ...prev,
      [eventName]: (prev[eventName] || 0) + 1
    }));
  };

  const close = () => setVisible(false);

  const handleCancel = () => {
    addLog('onCancel');
    if (topBarProps?.onCancel) topBarProps.onCancel();
    close();
  };

  const handleDone = () => {
    addLog('onDone');
    if (topBarProps?.onDone) topBarProps.onDone();
    close();
  };

  const handleBackgroundPress = () => {
    addLog('onBackgroundPress');
    if (modalProps.onBackgroundPress) {
      modalProps.onBackgroundPress();
    } else {
      close();
    }
  };

  const defaultTopBarProps = {
    title: label,
    onCancel: handleCancel,
    onDone: handleDone,
    cancelLabel: 'Cancel',
  };

  const finalTopBarProps = topBarProps === null 
    ? null 
    : {
        ...defaultTopBarProps, 
        ...topBarProps,
        onCancel: handleCancel, 
        onDone: handleDone
      };

  return (
    <View style={styles.testerWrapper}>
      <Button
        label={label}
        size={Button.sizes.xSmall}
        outline
        onPress={() => setVisible(true)}
        style={styles.triggerBtn}
      />
      
      {Object.keys(eventLogs).length > 0 && (
        <Text text100 grey40 style={{marginTop: 2}}>
          Log: {Object.entries(eventLogs).map(([k, v]) => `${k}(${v})`).join(', ')}
        </Text>
      )}

      <Modal
        visible={visible}
        onBackgroundPress={handleBackgroundPress}
        onRequestClose={close}
        animationType="slide"
        transparent={!isFullScreen}
        {...modalProps}
      >
        {isFullScreen ? (
          <View style={{flex: 1, backgroundColor: Colors.white}}>
             {finalTopBarProps && <Modal.TopBar {...finalTopBarProps} />}
             <View style={styles.modalContent}>
                <Text text60 style={styles.modalTitle}>{label}</Text>
                <View style={styles.modalBody}>
                  {children || <Text text70 grey40 center>全屏模式 (Full Screen)</Text>}
                </View>
                <Button
                  link
                  label="关闭弹窗"
                  onPress={close}
                  style={styles.closeBtn}
                />
             </View>
          </View>
        ) : (
          <View style={styles.modalOverlay} pointerEvents="box-none">
            <View style={styles.modalDialogContainer}>
              {finalTopBarProps && <Modal.TopBar {...finalTopBarProps} />}
              
              <View style={styles.modalContent}>
                <Text text60 style={styles.modalTitle}>{label}</Text>
                <View style={styles.modalBody}>
                  {children || <Text text70 grey40 center>这里是 Modal 内容区域</Text>}
                </View>
                <Button
                  link
                  label="关闭弹窗"
                  onPress={close}
                  style={styles.closeBtn}
                />
              </View>
            </View>
          </View>
        )}
      </Modal>
    </View>
  );
};

export default class ModalScreen extends Component {
  render() {
    return (
      <ScrollView contentContainerStyle={styles.scrollContainer}>
        <TestSuite name="Modal Props Comparison">
          
          <TestCase itShould="accessibilityLabel: 无障碍标签">
            <View row spread style={styles.row}>
              <ModalTester
                label="Label: Login"
                modalProps={{ accessibilityLabel: 'Login Modal Screen' }}
              />
              <ModalTester
                label="Label: Info"
                modalProps={{ accessibilityLabel: 'Information Dialog' }}
              />
            </View>
          </TestCase>

          <TestCase itShould="enableModalBlur (iOS): 启用原生模糊">
            <View row spread style={styles.row}>
              <ModalTester
                label="True"
                modalProps={{ enableModalBlur: true }}
              />
              <ModalTester
                label="False"
                modalProps={{ enableModalBlur: false }}
              />
            </View>
          </TestCase>

          <TestCase itShould="onBackgroundPress: 点击背景回调">
            <View row spread style={styles.row}>
              <ModalTester
                label="onBackgroundPress"
                 modalProps={{ onBackgroundPress: () => alert('onBackgroundPress') }}
              >
                <Text red30>请点击白色卡片外部区域查看日志</Text>
              </ModalTester>
            </View>
          </TestCase>

          <TestCase itShould="overlayBackgroundColor: 遮罩颜色">
            <View row spread style={styles.row}>
              <ModalTester
                label="Red 50%"
                modalProps={{ overlayBackgroundColor: 'rgba(255,0,0,0.5)' }}
              />
              <ModalTester
                label="Green 20%"
                modalProps={{ overlayBackgroundColor: 'rgba(0,255,0,0.2)' }}
              />
            </View>
          </TestCase>

          <TestCase itShould="testID: 测试标识符">
            <View row spread style={styles.row}>
              <ModalTester
                label="ID: modal_1"
                modalProps={{ testID: 'modal_test_1' }}
              />
              <ModalTester
                label="ID: modal_2"
                modalProps={{ testID: 'modal_test_2' }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: cancelButtonProps (取消按钮属性)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Red Color"
                topBarProps={{ cancelButtonProps: { color: Colors.red30 } }}
              />
              <ModalTester
                label="Outline"
                topBarProps={{ cancelButtonProps: { outline: true, color: Colors.blue30 } }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: cancelIcon (取消按钮图标)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Close Icon"
                topBarProps={{ cancelIcon: Assets.demo.close }}
              />
              <ModalTester
                label="Search Icon"
                topBarProps={{ cancelIcon: Assets.demo.searchs }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: cancelLabel (取消按钮文本)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Text: Cancel"
                topBarProps={{ cancelLabel: 'Cancel' }}
              />
              <ModalTester
                label="Text: Dismiss"
                topBarProps={{ cancelLabel: 'Dismiss' }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: containerStyle (容器样式)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Yellow Bg"
                topBarProps={{ containerStyle: { backgroundColor: Colors.yellow60 } }}
              />
              <ModalTester
                label="Border Bottom"
                topBarProps={{ containerStyle: { borderBottomWidth: 4, borderBottomColor: Colors.violet30 } }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: doneButtonProps (完成按钮属性)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Green Color"
                topBarProps={{ doneButtonProps: { color: Colors.green30 } }}
              />
              <ModalTester
                label="Disabled"
                topBarProps={{ doneButtonProps: { disabled: true } }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: doneIcon (完成按钮图标)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Check Icon"
                topBarProps={{ doneIcon: Assets.demo.check }}
              />
              <ModalTester
                label="Close Icon"
                topBarProps={{ doneIcon: Assets.demo.close }}
              />
            </View>
          </TestCase>

           <TestCase itShould="TopBar: doneLabel (完成按钮文本)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Text: Done"
                topBarProps={{ doneLabel: 'Done' }}
              />
              <ModalTester
                label="Text: Save"
                topBarProps={{ doneLabel: 'Save' }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: includeStatusBar (包含状态栏高度)">
            <View row spread style={styles.row}>
              <ModalTester
                label="True (Full Screen)"
                isFullScreen={true}
                topBarProps={{ includeStatusBar: true, containerStyle: {backgroundColor: Colors.grey70} }}
              />
              <ModalTester
                label="False (Full Screen)"
                isFullScreen={true}
                topBarProps={{ includeStatusBar: false, containerStyle: {backgroundColor: Colors.grey70} }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: leftButtons (左侧自定义按钮组)">
            <View row spread style={styles.row}>
              <ModalTester
                label="1 Button"
                topBarProps={{ 
                  onCancel: undefined,
                  leftButtons: [{ label: 'Back', onPress: ()=>Alert.alert('Back') }] 
                }}
              />
              <ModalTester
                label="2 Buttons"
                topBarProps={{ 
                  onCancel: undefined,
                  leftButtons: [
                    { icon: Assets.demo.close, onPress: ()=>{} },
                    { label: 'Info', onPress: ()=>Alert.alert('Info') }
                  ] 
                }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: onCancel (取消回调)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Log: Cancel A"
                topBarProps={{ onCancel: ()=>console.log('Cancel A triggered') }}
              />
              <ModalTester
                label="Log: Cancel B"
                topBarProps={{ onCancel: ()=>console.log('Cancel B triggered') }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: onDone (完成回调)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Log: Done A"
                topBarProps={{ onDone: ()=>console.log('Done A triggered') }}
              />
              <ModalTester
                label="Log: Done B"
                topBarProps={{ onDone: ()=>console.log('Done B triggered') }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: rightButtons (右侧自定义按钮组)">
            <View row spread style={styles.row}>
              <ModalTester
                label="1 Button"
                topBarProps={{ 
                  onDone: undefined,
                  rightButtons: [{ label: 'Next', onPress: ()=>Alert.alert('Next') }] 
                }}
              />
              <ModalTester
                label="2 Buttons"
                topBarProps={{ 
                  onDone: undefined,
                  rightButtons: [
                    { icon: Assets.demo.search, onPress: ()=>Alert.alert('Search') },
                    { label: 'Save', onPress: ()=>Alert.alert('Save') }
                  ] 
                }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: subtitle (副标题)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Sub: Description"
                topBarProps={{ subtitle: 'This is a description' }}
              />
              <ModalTester
                label="Sub: Note"
                topBarProps={{ subtitle: 'Important Note' }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: subtitleStyle (副标题样式)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Style: Italic"
                topBarProps={{ 
                  subtitle: 'Italic Grey',
                  subtitleStyle: { fontStyle: 'italic', color: Colors.grey40 } 
                }}
              />
              <ModalTester
                label="Style: Bold Red"
                topBarProps={{ 
                  subtitle: 'Bold Red',
                  subtitleStyle: { fontWeight: 'bold', color: Colors.red30 } 
                }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: title (主标题)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Title: Hello"
                topBarProps={{ title: 'Hello World' }}
              />
              <ModalTester
                label="Title: Settings"
                topBarProps={{ title: 'Settings Page' }}
              />
            </View>
          </TestCase>

          <TestCase itShould="TopBar: titleStyle (主标题样式)">
            <View row spread style={styles.row}>
              <ModalTester
                label="Serif Font"
                topBarProps={{ 
                  title: 'Serif Title',
                  titleStyle: { fontFamily: 'serif', color: Colors.blue10 } 
                }}
              />
              <ModalTester
                label="Large Red"
                topBarProps={{ 
                  title: 'Large Title',
                  titleStyle: { fontSize: 24, color: Colors.red10 } 
                }}
              />
            </View>
          </TestCase>

        </TestSuite>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  scrollContainer: {
    paddingBottom: 20,
    paddingHorizontal: 12,
  },
  row: {
    alignItems: 'flex-start',
    justifyContent: 'space-around',
    width: '100%',
  },
  testerWrapper: {
    alignItems: 'center',
    marginBottom: 8,
    width: '45%', // Ensure 2 items fit in a row
  },
  triggerBtn: {
    width: '100%',
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalDialogContainer: {
    width: '85%',
    height: '60%',
    backgroundColor: Colors.white,
    borderRadius: 16,
    overflow: 'hidden',
    elevation: 8,
    shadowColor: Colors.grey20,
    shadowOpacity: 0.5,
    shadowRadius: 10,
    shadowOffset: {width: 0, height: 4},
  },
  modalContent: {
    flex: 1,
    padding: Spacings.s5,
    alignItems: 'center',
  },
  modalTitle: {
    marginBottom: Spacings.s4,
    marginTop: Spacings.s2,
  },
  modalBody: {
    flex: 1,
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Colors.grey80,
    borderRadius: 8,
    marginBottom: Spacings.s5,
  },
  closeBtn: {
    marginBottom: Spacings.s5,
  },
  absoluteFill: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  }
});